#!/usr/bin/python3

'''wait and kill subprocess if it doesn't response (from network)'''

import os
import sys
import select
import subprocess

import prctl

timeout = 60

def new_group():
  os.setpgrp()

def main(args):
  strace_fifo = os.path.join('/tmp', '.' + '_'.join(args).replace('/', '-'))
  if not os.path.exists(strace_fifo):
    os.mkfifo(strace_fifo, 0o600)
  strace_out = os.open(strace_fifo, os.O_RDONLY | os.O_NONBLOCK)
  p = subprocess.Popen(['strace', '-o', strace_fifo, '-e', 'trace=network'] + args, preexec_fn=new_group)

  try:
    sig = 15
    while True:
      try:
        while os.waitid(os.P_ALL, 0, os.WEXITED | os.WNOHANG) is not None:
          pass
      except ChildProcessError:
        break

      ret = p.poll()
      if ret is not None:
        return ret
      rs, ws, xs = select.select([strace_out], (), (), timeout)
      if not rs:
        print('subprocess met network problem, killing with signal %d...' % sig, file=sys.stderr)
        os.kill(-p.pid, sig)
        sig = 9
      else:
        os.read(strace_out, 1024)
  except KeyboardInterrupt:
    os.kill(-p.pid, 15)

  return -1

if __name__ == '__main__':
  try:
    import setproctitle
    setproctitle.setproctitle('killhung')
    del setproctitle
  except ImportError:
    pass

  prctl.set_child_subreaper(1)
  sys.exit(main(sys.argv[1:]))
